<template>
  <div>
    <cus-modal ref="modal" :title="!form.materialId ? '添加食材' : '修改食材'" @on-visible-change="onVisibleChange" width="750"
      @onOk="onOk">
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="120">
        <FormItem label="食材名称:" prop="materialName">
          <Input v-model="form.materialName" clearable maxlength="20" style="width: 200px"
            :disabled="Boolean(form.materialId)" placeholder="请输入食材名称"></Input>
        </FormItem>
        <FormItem label="食材种类:" prop="foodClass" :rules="[
          { required: true, message: '食材种类不能为空', trigger: 'change' },
        ]">
          <Select v-model="form.foodClass" style="width: 200px" placeholder="请选择食材种类" clearable>
            <Option :value="item.name" v-for="(item, index) in materialTypeList" :key="index">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem v-if="!form.id" label="区域:" prop="kitchenArea" :rules="{
          required: true,
          message: '区域不能为空',
          trigger: 'change'
        }">
          <Select v-model="form.kitchenArea" style="width: 200px;" placeholder="请选择区域">
            <Option :value="item.kitchenArea" v-for="(item, index) in areaList" :key="index">
              {{ item.kitchenAreaName }}
            </Option>
          </select>
        </FormItem>
        <FormItem label="商品种类:" prop="productCategory" :rules="{
          required: true,
          message: '商品种类不能为空',
          trigger: 'change',
        }">
          <Select v-model="form.productCategory" style="width: 200px" placeholder="请选择商品种类" clearable>
            <Option :value="item.categoryName" v-for="(item, index) in productcategoryList" :key="index">{{
              item.categoryName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="是否称重出入库:" prop="weightFlag" :rules="[
          { required: true, message: '称重方式不能为空', trigger: 'change' },
        ]">
          <Select disabled v-model="form.weightFlag" placeholder="请选择称重方式" style="width: 200px">
            <Option value="0">否</Option>
            <Option value="1">是</Option>
          </Select>
        </FormItem>
        <FormItem label="是否常用:" prop="materialStatus" :rules="[
          { required: true, message: '是否常用不能为空', trigger: 'change' },
        ]">
          <Select v-model="form.materialStatus" placeholder="请选择称重方式" style="width: 200px" clearable disabled>
            <Option value="0">否</Option>
            <Option value="1">是</Option>
          </Select>
        </FormItem>
        <FormItem label="产地:" prop="province">
          <Select v-model="form.province" style="width: 200px" placeholder="请选择产地" clearable>
            <Option value="北京">北京</Option>
            <Option value="上海">上海</Option>
            <Option value="天津">天津</Option>
            <Option value="重庆">重庆</Option>
            <Option value="河北">河北</Option>
            <Option value="山西">山西</Option>
            <Option value="内蒙古">内蒙古</Option>
            <Option value="辽宁">辽宁</Option>
            <Option value="吉林">吉林</Option>
            <Option value="黑龙江">黑龙江</Option>
            <Option value="江苏">江苏</Option>
            <Option value="浙江">浙江</Option>
            <Option value="安徽">安徽</Option>
            <Option value="福建">福建</Option>
            <Option value="江西">江西</Option>
            <Option value="山东">山东</Option>
            <Option value="河南">河南</Option>
            <Option value="湖北">湖北</Option>
            <Option value="湖南">湖南</Option>
            <Option value="广东">广东</Option>
            <Option value="广西">广西</Option>
            <Option value="海南">海南</Option>
            <Option value="四川">四川</Option>
            <Option value="贵州">贵州</Option>
            <Option value="云南">云南</Option>
            <Option value="西藏">西藏</Option>
            <Option value="陕西">陕西</Option>
            <Option value="甘肃">甘肃</Option>
            <Option value="宁夏">宁夏</Option>
            <Option value="青海">青海</Option>
            <Option value="新疆">新疆</Option>
            <Option value="香港">香港</Option>
            <Option value="澳门">澳门</Option>
            <Option value="台湾">台湾</Option>
          </Select>
        </FormItem>
        <FormItem label="季节:" prop="quarterList">
          <Select v-model="form.quarterList" style="width: 200px" placeholder="请选择季节" clearable multiple>
            <Option value="春季">春季</Option>
            <Option value="夏季">夏季</Option>
            <Option value="秋季">秋季</Option>
            <Option value="冬季">冬季</Option>
          </Select>
        </FormItem>
        <FormItem label="计量单位:" prop="specification" :rules="[
          {
            required: true,
            message: '计量单位不能为空',
            trigger: 'change',
            type: 'number',
          },
        ]">
          <Select v-model="form.specification" style="width: 200px" placeholder="请选择计量单位" :disabled="form.id != undefined"
            @on-change="changeSpecification">
            <Option :value="item.specificationValue" v-for="(item, index) in specificationList" :key="index">{{
              item.specification }}</Option>
          </Select>
        </FormItem>
        <FormItem label="单位重量/kg:" prop="unitWeight">
          <InputNumber :min="0" v-model="form.unitWeight" style="width: 200px" 
           :disabled="form.specification == 0 || form.specification == 1 || form.id"></InputNumber>
        </FormItem>
        <FormItem label="价格:" prop="packagingPrice">
          <InputNumber  v-model="form.packagingPrice" style="width: 200px"></InputNumber>
        </FormItem>
        <FormItem label="折算比例(%):" prop="convertPro" :rules="[
          {
            required: true,
            message: '折算比例(%)不能为空',
            trigger: 'blur',
            type: 'number',
          },
        ]">
          <InputNumber :min="0" :max="100" v-model="form.convertPro" style="width: 200px"></InputNumber>
        </FormItem>
        <FormItem label="损耗率(%):" prop="storageLoss" :rules="[
          {
            required: true,
            message: '损耗率(%)不能为空',
            trigger: 'blur',
            type: 'number',
          },
        ]">
          <InputNumber :min="0" :max="100" v-model="form.storageLoss" style="width: 200px"></InputNumber>
        </FormItem>
        <FormItem label="规则分类:" prop="foodRuleClass">
          <Select v-model="form.foodRuleClass" style="width: 200px" placeholder="请选择规则分类" clearable>
            <Option :value="item.foodRuleName" v-for="(item, index) in foodRuleTypeList" :key="index">{{ item.foodRuleName
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="品牌:" prop="brand">
          <Input v-model="form.brand" clearable maxlength="20" style="width: 200px" placeholder="请输入品牌"></Input>
        </FormItem>
        <FormItem label="商品条形码:" prop="snCode">
          <Input v-model="form.snCode" :disabled="form.id != undefined" clearable maxlength="20" style="width: 200px"
            placeholder="请输入商品条形码"></Input>
        </FormItem>
        <FormItem label="库存预警:" prop="sellByDat">
          <InputNumber v-model="form.stockWarningPackagingQty" maxlength="20" :min="0" placeholder="请输入库存预警"
              style="width: 200px" @on-blur="inputBlur('stockWarningPackagingQty')">
            </InputNumber>

        </FormItem>
        <FormItem label="保质期(天):" prop="sellByDat">
          <InputNumber v-model="form.shelfLifeHour" maxlength="20" :min="0" placeholder="请输入保质期"
              style="width: 200px" @on-blur="inputBlur('shelfLifeHour')">

            </InputNumber>
        </FormItem>
    
      </Form>
    </cus-modal>
  </div>
</template>


<script>
const debounce = function (func, wait) {
  let timer;
  return function (that) {
    let context = that;
    let args = arguments;
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, wait);

  };
}
import {
  localFoodAdd,
  localFoodAlter,
  materialType,
  selectBasSpecificationList,
  getFoodRuleTypeList,
  getProductCategoryList,
  checkName,
  checkSN
} from "@/api/organ/dishesModule";
import { Option } from "view-design";

const form = {
  materialId: "",
  brand: "",
  convertPro: 100,
  foodClass: "",
  foodRuleClass: "",
  materialName: "",
  kitchenArea: "",
  packagingPrice: null,
  province: "",
  quarterList: [],
  snCode: "",
  specification: null,
  storageLoss: 5,
  unitWeight: 1,
  weightFlag: "1",
  materialStatus: "0",
  productCategory: "",
   // 库存预警重量
   stockWarningPackagingQty: '',
// 保质期
shelfLifeHour: ''
};

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      const selectValue = value.toString();
      console.log('sss', selectValue);
      if (/^(0|([1-9][0-9]*))(\.[\d]{1,2})?$/.test(selectValue)) {
        callback();
      } else {
        return callback(new Error("最多保留两位小数"));
      }
    };
    return {
      topLoading: true,
      form: form,
      ruleValidate: {
        materialName: [{ required: true, message: '食材名称不能为空', trigger: 'blur' },
        { validator: debounce(this.nameCheck, 500), trigger: 'change,blur' }],
        snCode: [
          { validator: debounce(this.SNCheck, 500), trigger: 'change' }],
        unitWeight: [
          {
            required: true,
            message: '单位重量不能为空',
            trigger: 'blur,change',
            type: 'number',
          },
          {
            required: true,
            min: 0.01,
            message: '单位重量最低为0.01',
            trigger: 'blur,change',
            type: 'number',
          },
          {
            // required: true,
            validator: validatePass,
            // pattern:'^(0|([1-9][0-9]*))(\.[\d]{1,2})?$',
            // message: '最多保留两位小数',
            trigger: 'blur,change',
            // type: 'number',
          }
        ],
        packagingPrice: [
        {
            required: true,
            message: '价格不能为空',
            trigger: 'blur,change',
            type: 'number',
          },
          {
            required: true,
            min: 0.01,
            message: '价格最低为0.01',
            trigger: 'blur,change',
            type: 'number',
          },
          {
            // required: true,
            validator: validatePass,
            // pattern:'^(0|([1-9][0-9]*))(\.[\d]{1,2})?$',
            // message: '最多保留两位小数',
            trigger: 'blur,change',
            // type: 'number',
          }
        ],
      },
      retMsg: '', //名称验证返回
      loading: false,
      materialTypeList: [],
      specificationList: [],
      foodRuleTypeList: [],
      productcategoryList: [],
      areaList: this.$store.state.selectList.areaList,
    };
  },
  mounted() {
    this.form = this.$cu.deepClone(form);
  },
  methods: {
    // 处理两位小数
    floatInput(val) {
      console.log(val);
      let checkPlan = "" + val;
      checkPlan = checkPlan
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + "";
      } else if (checkPlan.indexOf(".") >= 0) {
        checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      }
      this.$nextTick(() => (this.form.unitWeight = checkPlan * 1));
      return checkPlan;
    },
    // input失焦
    inputBlur(key) {
      console.log(this.form[key]);
      if (this.form[key] == null) this.form[key] = 0

    },

    onVisibleChange(v) {
      if (!v) {
        this.$refs["formValidate"].resetFields();
        this.form = this.$cu.deepClone(form);
      }
    },
    show() {
      this.$refs["modal"].show = true;
      this.form.kitchenArea = this.form.kitchenArea ? this.form.kitchenArea : this.areaList[0].kitchenArea
      this.materialTypeApi();
      this.selectBasSpecificationListApi();
      this.getFoodRuleTypeListApi();
      this.productcategoryApi();
    },
    onOk() {
      this.$refs["formValidate"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.materialId) {
            this.localFoodAlterApi();
          }
          else {
            console.log(1111);
            this.localFoodAddApi();
          }
        }

      });
    },
    // 判断SN码是否重复
    SNCheck(rule, value1, callback) {
      if (value1) {
        this.getSNCheckApi().then(
          (value) => {
            console.log(value);
            if (value != 'ok') {
              return callback(value)
            } else {
              console.log(11111);
              return callback()
            }
          })
      } else {
        return callback()
      }
    },
    getSNCheckApi() {
      return new Promise((resolve) => {
        checkSN({
          kitchenArea: this.form.kitchenArea,
          id: this.form.id,
          snCode: this.form.snCode
        }).then((res) => {
          resolve(res.msg)
        })
      })
    },
    // 判断名称是否重复
    nameCheck(rule, value1, callback) {
      if (value1 && !this.form.materialId) {
        this.getCheckNameApi().then(
          (value) => {
            console.log(value);
            if (value != 'ok') {
              return callback(value)
            } else {
              return callback()
            }
          }
        )
      } else {
        return callback()
      }
    },
    // 判断名称是否重复APi
    getCheckNameApi() {
      return new Promise((resolve) => {
        checkName({
          kitchenArea: this.form.kitchenArea,
          materialName: this.form.materialName
        }).then((res) => {
          resolve(res.msg)
        })
      })
    },
    // 计量单位变更
    changeSpecification(value) {
      console.log("value---" + value);
      this.form.weightFlag = '0'
      if (value == 0) {
        this.form.unitWeight = 1;
        this.form.weightFlag = '1'
      }
      if (value == 1) {
        this.form.unitWeight = 0.5;
        this.form.weightFlag = '1'
      }
    },
    // 添加食材
    localFoodAddApi() {
      this.loading = true;
      return new Promise((resolve) => {
        localFoodAdd(this.form).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$Message.success("添加成功");
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    // 编辑食材
    localFoodAlterApi() {
      this.loading = true;
      return new Promise((resolve) => {
        localFoodAlter(this.form).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            this.$Message.success("编辑成功");
            this.$refs["modal"].show = false;
            this.$parent.onInit();
            resolve();
          }
        });
      });
    },
    // 获取食材种类
    materialTypeApi() {
      return new Promise((resolve) => {
        materialType({}).then((res) => {
          if (res.code === 1) {
            this.materialTypeList = res.data;
            resolve();
          }
        });
      });
    },
    // 获取食材规格
    selectBasSpecificationListApi() {
      return new Promise((resolve) => {
        selectBasSpecificationList({}).then((res) => {
          if (res.code === 1) {
            this.specificationList = res.data;
            if (res.data.length && !this.form.materialId) {
              this.form.specification = res.data[0].specificationValue;
              if(this.form.specification == 0 || this.form.specification == 1) {
                this.form.weightFlag = '1';
              }
            }
            resolve();
          }
        });
      });
    },
    getFoodRuleTypeListApi() {
      return new Promise((resolve) => {
        getFoodRuleTypeList({}).then((res) => {
          if (res.code === 1) {
            this.foodRuleTypeList = res.data;
            resolve();
          }
        });
      });
    },
    // 获取商品分类
    productcategoryApi() {
      return new Promise((resolve) => {
        getProductCategoryList({
          size: 100,
        }).then((res) => {
          if (res.code === 1) {
            this.productcategoryList = res.data;
            resolve();
          }
        });
      });
    },
  },
  components: { Option }
};
</script>

<style scoped>
/deep/.ivu-select-multiple .ivu-select-selection .ivu-select-placeholder {
  /* height: 40px !important; */
  height: auto !important;
  line-height: 40px !important;
}

/*  取消input框加载环 */
/deep/ .ivu-icon-ios-loading:before {
  display: none;
}

/deep/ .ivu-select-multiple .ivu-select-selection .ivu-select-placeholder {
  height: 32px;
  line-height: 32px !important;
}

/deep/ #html .ivu-input-number-handler {
  height: null !important;
}

/deep/ .ivu-input-number-input-wrap {
  height: 32px !important;
  line-height: 32px !important;
}

/deep/.ivu-select-selection {
  height: auto !important;
  min-height: 32px !important;
  border-radius: 2px !important;
}
</style>

<style scoped lang="less">
.permission {
  height: 300px;
  width: 500px;
  border: 1px solid #dcdee2;
  overflow-y: auto;
  border-radius: 2px;
  padding: 0 0 0 10px;
}
</style>
